package com.dyy.AI_System.controller;

import com.dyy.AI_System.domain.po.Documents;
import com.dyy.AI_System.domain.po.Users;
import com.dyy.AI_System.domain.po.Departments;
import com.dyy.AI_System.domain.po.DocumentCategories;
import com.dyy.AI_System.domain.vo.ApiResponse;
import com.dyy.AI_System.service.IDocumentsService;
import com.dyy.AI_System.mapper.UsersMapper;
import com.dyy.AI_System.mapper.DepartmentsMapper;
import com.dyy.AI_System.mapper.DocumentCategoriesMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 文档表 前端控制器
 * </p>
 *
 * @author dyy
 * @since 2025-10-14
 */
@Tag(name = "文档管理", description = "文档相关的CRUD操作API")
@RestController
@RequestMapping("/api/documents")
public class DocumentsController {

    @Autowired
    private IDocumentsService documentsService;
    
    @Autowired
    private UsersMapper usersMapper;
    
    @Autowired
    private DepartmentsMapper departmentsMapper;
    
    @Autowired
    private DocumentCategoriesMapper documentCategoriesMapper;
    
    /**
     * 上传文档
     */
    @Operation(summary = "上传文档", description = "将文档上传至系统并创建文档记录")
    @PostMapping("/upload")
    public ResponseEntity<ApiResponse<Map<String, Object>>> uploadDocument(
            @RequestParam("file") MultipartFile file,
            @RequestParam("departmentId") Long departmentId,
            @RequestParam("categoryId") Long categoryId,
            @RequestParam("description") String description,
            @RequestParam("accessLevel") String accessLevel,
            @RequestParam("tags") List<String> tags) {
        try {
            // 这里假设从Token中获取上传者ID，暂时使用固定值1
            Long uploaderId = 1L;
            
            Map<String, Object> result = documentsService.uploadDocument(
                    file, departmentId, categoryId, description, accessLevel, tags, uploaderId);
            
            return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success("上传成功", result));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "上传失败: " + e.getMessage()));
        }
    }
    
    /**
     * 获取文档列表
     */
    @Operation(summary = "获取文档列表", description = "分页查询文档列表，支持按部门、分类和状态筛选")
    @GetMapping
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDocumentList(
            @RequestParam(name="page",defaultValue = "1") Integer page,
            @RequestParam(name="size",defaultValue = "20") Integer size,
            @RequestParam(name="departmentId",required = false) Long departmentId,
            @RequestParam(name="categoryId",required = false) Long categoryId,
            @RequestParam(name="status",required = false) String status) {
        
        IPage<Documents> documentPage = documentsService.pageQuery(page, size, departmentId, categoryId, status);
        
        // 构建响应数据，包含嵌套的关联信息
        List<Map<String, Object>> documentList = documentPage.getRecords().stream().map(document -> {
            Map<String, Object> documentMap = new HashMap<>();
            documentMap.put("id", document.getId());
            documentMap.put("title", document.getTitle());
            documentMap.put("fileType", document.getFileType());
            documentMap.put("fileSize", document.getFileSize());
            
            // 添加上传者信息
            Users uploader = usersMapper.selectById(document.getUploaderId());
            Map<String, Object> uploaderMap = new HashMap<>();
            uploaderMap.put("id", uploader.getId());
            uploaderMap.put("name", uploader.getName());
            documentMap.put("uploader", uploaderMap);
            
            // 添加部门信息
            Departments department = departmentsMapper.selectById(document.getDepartmentId());
            Map<String, Object> departmentMap = new HashMap<>();
            departmentMap.put("id", department.getId());
            departmentMap.put("name", department.getName());
            documentMap.put("department", departmentMap);
            
            // 添加分类信息
            DocumentCategories category = documentCategoriesMapper.selectById(document.getCategoryId());
            Map<String, Object> categoryMap = new HashMap<>();
            categoryMap.put("id", category.getId());
            categoryMap.put("name", category.getName());
            documentMap.put("category", categoryMap);
            
            // 添加其他信息
            documentMap.put("status", document.getStatus());
            documentMap.put("accessLevel", document.getAccessLevel());
            documentMap.put("createdAt", document.getCreatedAt());
            documentMap.put("processedAt", document.getProcessedAt());
            
            return documentMap;
        }).collect(Collectors.toList());
        
        // 构建分页响应
        Map<String, Object> response = new HashMap<>();
        response.put("list", documentList);
        response.put("total", documentPage.getTotal());
        response.put("page", documentPage.getCurrent());
        response.put("size", documentPage.getSize());
        
        return ResponseEntity.ok(ApiResponse.success(response));
    }
    
    /**
     * 获取文档详情
     */
    @Operation(summary = "获取文档详情", description = "根据文档ID查询文档的详细信息，包含关联的上传者、部门和分类信息")
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getDocumentDetail(@PathVariable("id") Long id) {
        try {
            Map<String, Object> documentDetail = documentsService.getDocumentDetail(id);
            return ResponseEntity.ok(ApiResponse.success(documentDetail));
        } catch (RuntimeException e) {
            return ResponseEntity.ok(ApiResponse.fail(404, e.getMessage()));
        }
    }
    
    /**
     * 删除文档
     */
    @Operation(summary = "删除文档", description = "根据文档ID删除文档记录和对应的文件")
    @DeleteMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> deleteDocument(@PathVariable("id") Long id) {
        try {
            documentsService.deleteDocument(id);
            return ResponseEntity.ok(ApiResponse.success("删除成功", null));
        } catch (RuntimeException e) {
            return ResponseEntity.ok(ApiResponse.fail(404, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "删除失败: " + e.getMessage()));
        }
    }
    
    /**
     * 更新文档信息
     */
    @Operation(summary = "更新文档信息", description = "更新指定ID文档的基本信息，包括标题、描述、分类、访问级别和标签")
    @PutMapping("/{id}")
    public ResponseEntity<ApiResponse<Object>> updateDocumentInfo(@PathVariable("id") Long id, @RequestBody Map<String, Object> updateInfo) {
        try {
            
            String title = (String) updateInfo.get("title");
            String description = (String) updateInfo.get("description");
            Long categoryId = ((Number) updateInfo.get("categoryId")).longValue();
            String accessLevel = (String) updateInfo.get("accessLevel");
            List<String> tags = Optional.ofNullable(updateInfo.get("tags"))
                    .filter(obj -> obj instanceof List)
                    .map(obj -> ((List<?>) obj).stream()
                            .filter(String.class::isInstance)
                            .map(String.class::cast)
                            .collect(Collectors.toList()))
                    .orElse(Collections.emptyList());
            
            documentsService.updateDocumentInfo(id, title, description, categoryId, accessLevel, tags);
            
            return ResponseEntity.ok(ApiResponse.success("更新成功", null));
        } catch (RuntimeException e) {
            return ResponseEntity.ok(ApiResponse.fail(404, e.getMessage()));
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(ApiResponse.fail(500, "更新失败: " + e.getMessage()));
        }
    }
}
